﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace MethodWorx.Core
{
    public class MimeTypes
    {
        private static Dictionary<string, string> types = new Dictionary<string, string>();
        static MimeTypes()
        {
            using(var stream = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MethodWorx.Core.MimeTypes.txt")))
            {
                var regex = new Regex(@"\s+");
                while(true)
                {
                    var line = stream.ReadLine();
                    if (line == null)
                        break;

                    //
                    //  ok, split the line up
                    line = regex.Replace(line, @" ");
                    //  now slit
                    var entries = line.Split(new char [] {' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (entries.Length >= 2 && !types.ContainsKey(entries[0].ToLower()))
                        types.Add(entries[0].ToLower(), entries[1]);
                }
            }
        }

        public static string GetMimeTypeFromExtension(string extension, string defaultMimeType)
        {
            extension = "." + (extension.Trim().TrimStart('.'));

            if (types.ContainsKey(extension.ToLower()))
                return types[extension.ToLower()];
            else
            {
                return defaultMimeType;
            }
        }
    }
}
